package utils

import (
	"fmt"
	"strconv"
	"time"

	"github.com/golang-jwt/jwt/v4"

	"probe-users/internal/errorx"
)

type Claims struct {
	UserId   int64  `json:"user_id"`
	Username string `json:"username"`
	RoleId   int64  `json:"role_id"`
	jwt.RegisteredClaims
}

// GenerateToken 生成JWT令牌
func GenerateToken(userId int64, username string, roleId int64, secret string, expire int64) (string, error) {
	// 设置过期时间
	expirationTime := time.Now().Add(time.Duration(expire) * time.Second)

	// 创建claims
	claims := &Claims{
		UserId:   userId,
		Username: username,
		RoleId:   roleId,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "usercenter",
			Subject:   "user",
		},
	}

	// 创建token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// 签名token
	tokenString, err := token.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

// ParseToken 解析JWT令牌
func ParseToken(tokenString string, secret string) (*Claims, error) {
	// 解析token
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})

	if err != nil {
		return nil, fmt.Errorf("%w: 解析token失败: %v", errorx.ErrInvalidToken, err)
	}

	// 验证token
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}

	return nil, errorx.ErrInvalidToken
}

// StringToInt64 字符串转int64
func StringToInt64(s string) (int64, error) {
	return strconv.ParseInt(s, 10, 64)
}
